/*
 * Copyright (c) 2011-2024, baomidou (jobob@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.rainman.mybatisplus.plugins_up3_5_x;

import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.rainman.mybatisplus.core.JoinStrUtil;
import com.rainman.mybatisplus.joinparam.JoinParam;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.sql.SQLException;
import java.util.Map;
import java.util.Optional;

/**
 * 3_5_x以上连表拦截器
 *
 * @author lqy
 *
 */
@SuppressWarnings({"rawtypes"})
public class JoinInterceptor implements InnerInterceptor {

    private String loginDelField=null;

    public JoinInterceptor(){
    }

    public JoinInterceptor(String loginDelField){
        this.loginDelField=loginDelField;
    }



    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter,
                            RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {


        JoinParam joinParam=findJp(parameter).orElse(null);
        if (joinParam == null ) {
            return;
        }



        String sql1 = boundSql.getSql();
        //System.out.println("原始的sql"+sql1);
        StringBuilder sb = new StringBuilder(sql1+" ");


        //找出原字段 判断是否加asname 去除ex字段---------------------------
        JoinStrUtil.dealSelect(sb,joinParam);


        //找出表字段 加asName------------------------------
        JoinStrUtil.dealJoinInfo(sb,joinParam);


        //处理逻辑删除-------------------
        String finalSt=sb.append(" ").toString();
        if(loginDelField!=null){
            finalSt=finalSt.replaceAll(loginDelField+"=",joinParam.getAsName()+"."+loginDelField+"=");
        }


        PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);
        mpBs.sql(finalSt);


        return;
    }



    private  Optional<JoinParam> findJp(Object parameterObject) {
        if (parameterObject != null) {
            if (parameterObject instanceof Map) {
                Map<?, ?> parameterMap = (Map<?, ?>) parameterObject;
                for (Map.Entry entry : parameterMap.entrySet()) {
                    if (entry.getValue() != null && entry.getValue() instanceof JoinParam) {
                        return Optional.of((JoinParam) entry.getValue());
                    }
                }
            } else if (parameterObject instanceof JoinParam) {
                return Optional.of((JoinParam) parameterObject);
            }
        }
        return Optional.empty();
    }

}
